<?php
/**
 * Created by PhpStorm.
 * User: edmmss
 * Date: 2019/1/15
 * Time: 09:08
 */

namespace app\modules\strategy\controller;

use app\modules\strategy\Context;
use app\modules\strategy\DateComparator;
use app\modules\strategy\IdComparator;
use yii\web\Controller;

class DefaultController extends Controller
{
    /**
     * 策略模式示例
     * 分离「策略」并使他们之间能互相快速切换
     * 此外，这种模式是一种不错的继承替代方案（替代使用扩展抽象类的方式）
     *
     * @date   2019/1/15
     * @author edmmss
     * @return bool
     */
    public function actionIndex()
    {
        $integers = $this->provideIntegers();
        $dates = $this->provideDates();

        $obj = new Context(new IdComparator());
        $elements = $obj->executeStrategy($integers);

        var_dump($elements);

        $obj = new Context(new DateComparator());
        $elements = $obj->executeStrategy($dates);

        var_dump($elements);

        return true;
    }

    private function provideIntegers()
    {
        return [
            ['id' => 3],
            ['id' => 2],
            ['id' => 20],
            ['id' => 10],
            ['id' => 23],
            ['id' => 1],
            ['id' => 5],
        ];
    }

    private function provideDates()
    {
        return [
            ['date' => '2018-11-08'],
            ['date' => '2018-11-01'],
            ['date' => '2019-11-08'],
            ['date' => '2018-12-08'],
            ['date' => '2018-05-12'],
            ['date' => '2018-11-05'],
        ];
    }
}